<?php
require_once 'BaseController.php';

/**
 * エリア検索クラス<br />
 *
 * @package    apamanshop
 * @author     SS山本
 * @copyright
 */
class Search_AreasearchController extends Search_BaseController
{
	public function indexAction()
	{
		/*エリア検索使わない*/
		$this->my_redirect('sitemap/404error.html');
		
		$this->setMainTemplate('cms_search.tpl');
		/*
		 * 基本情報設定
		 */
		// 検索区分
		$this->setSearchKbn(Apm_Config_Search::SRHKBN_AREA, "areasearch");

		if (Apm_Config_Search::RENEW_2012 && $this->_static_pattern == 'chiiki') {
			$this->_display_path = APPLICATION_PATH . '/modules/search/views/scripts/search_new.tpl';
			$this->_newTemplate = true;
			$this->_import_seo_search = true;
			// テンプレート変更
			$this->_area_helper = $this->getApmHelper('selarea_new.tpl');
			// JavaScript
			$this->addMetaJs('/common_new/js/import.js');
			// CSS
			$this->addMetaCss('/common_new/css/sub02.css',array('type' => 'text/css','media' => 'all'));
		} else {
			$this->_display_path = APPLICATION_PATH . '/modules/search/views/scripts/search.tpl';
			//CSSの定義（デザイン）
			$this->addMetaCss('/css/search/search.css',array('type' => 'text/css','media' => 'all'));
			$this->addMetaCss('/css/shop/shop.css',array('type' => 'text/css','media' => 'all'));
		}

		// ページ見出し設定
		$this->_data['h1_title'] = 'ご希望の条件を選択してください。';

		/*
		 * モデルオブジェクト生成
		 */
		$this->_model_area = new Search_Model_Selareasearch();

		// 店舗URL設定
		//$this->setUrlParams();

		// 都道府県TOP => 住所検索へ統合
		if ($this->_model_common->checkvalue($this->_params, "PrefCd"))
		{
			// 政令指定都市・市区町村取得
			// 店舗一覧
		}
		// エリアTOP
		else if ($this->_model_common->checkvalue($this->_params, "AreaCd"))
		{
			if ($this->_newTemplate) {
				// ブロックタイトル
				$this->_data['block_title'] = 'エリアで絞り込む';
				// リード文
				$this->_data['block_text'] = Apm_Config_Search::SEOSTR_AREASTR.'{&nbsp;の}'.Apm_Config_Search::SEOSTR_KODAWARI.'{な}'
											.Apm_Config_Search::ALIAS_TYPE.'情報をエリアで絞り込みたい方はこちらから。';
			} else {
				// ブロックタイトル
				$this->_data['block_title'] = 'エリアで絞り込む';
				// リード文
				$this->_data['block_text'] = Apm_Config_Search::SEOSTR_AREASTR.'{の}'.Apm_Config_Search::SEOSTR_KODAWARI.'{な}'
											.Apm_Config_Search::ALIAS_TYPE.'情報をエリアで絞り込みたい方はこちらから。';
			}

			// 都道府県取得
			$this->_data['selpref'] = array();
			$this->_data['selpref'] = $this->_model_area->getAreaListByAreaCd($this->_params);
			$prefList['PrefCd']     = $this->_model_area->convertAreaPrefData($this->_data, $this->_params);
			$this->_data['area_name'] = $this->_data['selpref'][0]['M01_AREA_NAME'];

			// 政令指定都市・市区町村取得
			$prefList['TatemonoTypeCd'] = $this->_params['TatemonoTypeCd'];
			$prefList['KodawariId']     = $this->_params['KodawariId'];
			$this->_data['selcity'] = array();
			$this->_data['selcity'] = $this->_model_area->getPopCityListByPrefCd($prefList);
			$this->_model_area->convertAreaCityData($this->_data, $this->_params);

			// 店舗一覧
		}

		// Helper設定
		$this->_main_helper = $this->_area_helper;
		// モバイルAPIデータの作成
		$this->mobileApiAct($this->_data['Mapping']);
	}

	public function _indexbackAction()
	{

		/*
		 * 基本情報設定
		 */
		// 検索区分
		$this->setSearchKbn(Apm_Config_Search::SRHKBN_AREA, "areasearch");

		//CSSの定義（デザイン）
		$this->addMetaCss('/css/search/search.css',array('type' => 'text/css','media' => 'all'));

		//JavaSriptの定義（アプリ）
		$this->addMetaJs($this->_aplbaseurl . '/js/search/Selcyo.js');
		$this->addMetaJs($this->_aplbaseurl . '/js/search/Selsikucyoson.js');
		$this->addMetaJs($this->_aplbaseurl . '/js/search/Seltodohuken.js');
		$this->addMetaJs($this->_aplbaseurl . '/js/search/Areasearch.js');

		// ページ見出し設定
		$this->_data['h1_title'] = 'ご希望の条件を選択してください。';

		/*
		 * モデルオブジェクト生成
		 */
		$this->_model_sikucyoson = new Search_Model_Selsikucyoson();
		$this->_model_ensen      = new Search_Model_Selensen();
		$this->_model_eki        = new Search_Model_Seleki();
		$this->_model_research   = new Search_Model_ResearchPanel();
		$this->_model_campain    = new Search_Model_Campaignsearch();

        // 店舗URL設定
        $this->setUrlParams();

		// セレクトメニュー用変数
		$selectData = array();

		/*
		 * 検索画面振り分け
		 */
		// 非同期通信：市区町村取得
		if (   $this->_model_common->checkvalue($this->_params, "AjaxFlg")
		    && $this->_model_common->returnValue($this->_params, "Type") == 'jyusyo')
		{

			$prefcd = $this->_params['PrefCd'];

			$this->_params['PrefCd'] = array();
			$this->_params['PrefCd'][0] = $prefcd;

			// SELECTボックス生成
			$html = $this->createCitySelectHtml($this->_params);

			Apm_Util::outputXPassThroutgh();
			echo $html;
			exit;

		}
        // 非同期通信：沿線取得
		elseif (   $this->_model_common->checkvalue($this->_params, "AjaxFlg")
		        && $this->_model_common->returnValue($this->_params, "Type") == 'enseneki')
		{

			$prefcd = $this->_params['PrefCd'];

			$this->_params['PrefCd'] = array();
			$this->_params['PrefCd'][0] = $prefcd;

			// SELECTボックス生成
			$html = $this->createRailSelectHtml($this->_params);

			Apm_Util::outputXPassThroutgh();
			echo $html;
			exit;

		}
        // 都道府県検索
		elseif ($this->_model_common->checkvalue($this->_params, "PrefCd"))
		{

			// エリア検索モデルオブジェクト生成
			$this->_model_area = new Search_Model_Selareasearch();

			// 都道府県セレクト内容取得
			$selectData['selpref'] = array();
			$selectData['selpref'] = $this->_model_area->getAreaListByPrefCd($this->_params);

			// 市区町村セレクト内容
			$selectData['selcity'] = $this->createCitySelectHtml($this->_params);
			//$selectData['selcity'] = array();
			//$selectData['selcity'] = $this->_model_sikucyoson->getShikucyosonData($this->_params);

			//$this->_data['selcity'] = $selectData['selcity'];

			// 表示用データに変換
			$selectData['selensen'] = $this->createRailSelectHtml($this->_params);
			//$this->_model_sikucyoson->convertShikucyosonData($selectData);

			// 沿線セレクト内容
			//$selectData['selensen'] = array();
			//$selectData['selensen'] = $this->_model_ensen->getEnsenData($this->_params);

			//$this->_data['selensen'] = $selectData['selensen'];

			// 表示用データに変換
			//$this->_model_ensen->convertEnsenData($selectData);

			// 初期セレクト
			$selectData['check'] = $this->_params['PrefCd'][0];

			// セレクト内容格納
			$this->_data['select_data'] = array( 'check'    => $selectData['check']
			                                    ,'selpref'  => $selectData['selpref']
			                                    ,'selcity'  => $selectData['selcity']
			                                    ,'selensen' => $selectData['selensen']);

			// 電話番号一覧取得
            $preflist = $this->_model_area->getAreaListByPrefCd($this->_params);
            $tellist = $this->_model_area->getSearchShopList($preflist);
            $this->_data['tellist'] = $this->_model_area->convertShopListData($tellist, $preflist);

			$this->_main_helper = $this->_area_helper;
		}
		// エリア検索
		else if ($this->_model_common->checkvalue($this->_params, "AreaCd"))
		{

			// エリア検索モデルオブジェクト生成
			$this->_model_area = new Search_Model_Selareasearch();

			// 都道府県セレクト内容取得
			$selectData['selpref'] = array();
			$selectData['selpref'] = $this->_model_area->getAreaListByAreaCd($this->_params);

			// 市区町村セレクト内容
			$selectData['selcity'] = $this->createCitySelectHtml($this->_params, false);
			//$selectData['selcity'] = array();

			// 沿線セレクト内容
			$selectData['selensen'] = $this->createRailSelectHtml($this->_params, false);
			//$selectData['selensen'] = array();

// TODO
//   ---- COMMENT START ----
//   一覧表示用のプログラム
//   表示しないため、コメントアウトしておく
//			// 表示用データに変換
//			$this->_model_sikucyoson->convertShikucyosonData($selectData);
//			$this->_model_sikucyoson->convertShikucyosonData($this->_data);

//			/*
//			 * 市区町村名順に表示する
//			 */
//			$this->_model_sikucyoson->sortShikucyosonData($this->_data['Mapping'], $this->_params['PrefCd']);

//			$selectData['selensen'] = array();
//			$selectData['selensen'] = $this->_model_ensen->getEnsenData($this->_params);
//
//			$this->_data['selensen'] = $selectData['selensen'];

//			// 表示用データに変換
//			$this->_model_ensen->convertEnsenData($selectData);
//   ---- COMMENT END ----


			// 初期セレクト
			$selectData['check'] = NULL;

			// セレクト内容格納
			$this->_data['select_data'] = array( 'check'    => $selectData['check']
			                                    ,'selpref'  => $selectData['selpref']
			                                    ,'selcity'  => $selectData['selcity']
			                                    ,'selensen' => $selectData['selensen']);

			// 電話番号一覧取得
            $preflist = $this->_model_area->getAreaListByAreaCd($this->_params);
            $tellist = $this->_model_area->getSearchShopList($preflist);
            $this->_data['tellist'] = $this->_model_area->convertShopListData($tellist, $preflist);

			$this->_main_helper = $this->_area_helper;
		}
		else
		{

			// TODO
			// エリアページTOP？？
			// エリア情報をすべて出す？？

		}
		// モバイルAPIデータの作成
		$this->mobileApiAct($this->_data['Mapping']);

        // 表示
		$this->_display_path = APPLICATION_PATH . '/modules/search/views/scripts/areasearch.tpl';

	}

	public function createCitySelectHtml(&$params, $output=true) {
		// 市区町村セレクト内容
		$selSiku = array();
		$selCity = array();
		if ($output) {
			$prefcd = $params['PrefCd'][0];
			$selectData = array();
			$selectData['selcity'] = $this->_model_sikucyoson->getShikucyosonData($params);
			$this->_model_sikucyoson->convertShikucyosonData($selectData);
			Apm_Bukkenurl::generateSearchStaticUrl($this->_params, $selectData['Mapping'], Apm_Config_Search::SRHKBN_JYUSYO);
			if (!empty($selectData['Mapping'][$prefcd]['SITEITOSI_DATA'])) {
				$selSiku = &$selectData['Mapping'][$prefcd]['SITEITOSI_DATA'];
			}
			if (!empty($selectData['Mapping'][$prefcd]['SHIKUCHOUSON_DATA'])) {
				$selCity = &$selectData['Mapping'][$prefcd]['SHIKUCHOUSON_DATA'];
			}
		}
		
		$select_html = "";
		$hidden_html = "";
		$select_html .= "<select name='AreaCityCd' id='AreaCityCd'>";
		$select_html .= "<option value=''>市区町村を選択してください</option>";
		
		reset($selSiku);
		while (list($sKey, $sVal) = each($selSiku)) {
			$selSikuCity = $sVal['SITEI_SIKU_DATA'];
			foreach ($selSikuCity as $key => $val) {
				$select_html .= "<option value='" . $val['SHIKUCHOUSON_CD'] ."'>";
				$select_html .= $val['SHIKUCHOUSON'] ."</option>";
				$hidden_html .= "<input type='hidden' name='CityStatic_" . $val['SHIKUCHOUSON_CD'] . "' id='CityStatic_" . $val['SHIKUCHOUSON_CD'] . "' value='" . substr($val['STATIC_URL'],1) . "'>";
			}
		}
		foreach ($selCity as $key => $val) {
			$select_html .= "<option value='" . $val['SHIKUCHOUSON_CD'] ."'>";
			$select_html .= $val['SHIKUCHOUSON'] ."</option>";
			$hidden_html .= "<input type='hidden' name='CityStatic_" . $val['SHIKUCHOUSON_CD'] . "' id='CityStatic_" . $val['SHIKUCHOUSON_CD'] . "' value='" . substr($val['STATIC_URL'],1) . "'>";
		}
/*			
		foreach($selsity as $key => $val){
			$select_html .= "<option value='" . $val['SHIKUCHOUSON_CD'] ."'>";
			$select_html .= $val['SHIKUCHOUSON'] ."</option>";
		}
*/			
		$select_html .= "</select>";
		
		return $select_html . $hidden_html;
	}

	public function createRailSelectHtml(&$params, $output=true) {
		// 沿線セレクト内容
		$selRailKbn = array();
		if ($output) {
			$prefcd = $params['PrefCd'][0];
			$selectData = array();
			$selectData['selensen'] = $this->_model_ensen->getEnsenDataByMulti($params);
			$this->_model_ensen->convertEnsenDataByMulti($selectData);
			Apm_Bukkenurl::generateSearchStaticUrl($this->_params, $selectData['Mapping'], Apm_Config_Search::SRHKBN_ENSENEKI);
			$selRailKbn = $selectData['Mapping'][$prefcd]['EnsenKbnList'];
		}
		
		$select_html = "";
		$hidden_html = "";
		$select_html .= "<select name='AreaRailCd' id='AreaRailCd'>";
		$select_html .= "<option value=''>路線を選択してください</option>";
		
		reset($selRailKbn);
		while (list($sKey, $sVal) = each($selRailKbn)) {
			$selRail = $sVal['RailList'];
			foreach ($selRail as $key => $val) {
				$select_html .= "<option value='" . $val['T57_ENSEN_SHIKUCHOUSON_CD'] ."'>";
				$select_html .= $val['ENSEN_NAME'] ."</option>";
				$hidden_html .= "<input type='hidden' name='RailStatic_" . $val['T57_ENSEN_SHIKUCHOUSON_CD'] . "' id='RailStatic_" . $val['T57_ENSEN_SHIKUCHOUSON_CD'] . "' value='" . substr($val['STATIC_URL'],1) . "'>";
			}
		}
/*
		foreach($selensen as $key => $val){
			$select_html .= "<option value='" . $val['T57_ENSEN_SHIKUCHOUSON_CD'] ."'>";
			$select_html .= $val['T57_ENSEN_SHIKUCHOUSON_NAME'] ."</option>";
		}
*/
		$select_html .= "</select>";
		
		return $select_html . $hidden_html;
	}

	public function prefAction()
	{
		if (empty($this->_params['PrefCd'])) {
			Apm_Util::redirect($this->_baseurl.'search/jyusyosearch/');
		}
		if (!is_array($this->_params['PrefCd'])) {
			$prefCd = $this->_params['PrefCd'];
			$this->_params['PrefCd'] = array($prefCd);
		}
		if (empty($this->_params['PrefName'])) {
			$this->_params['PrefName'] = Apm_Config_Search::$TODOUFUKEN_NAME_CODE_LIST[$prefCd];
		}
		// 検索区分
		$this->setSearchKbn(Apm_Config_Search::SRHKBN_AREA, "jyusyosearch");
		// メインテンプレート
		$this->_display_path = APPLICATION_PATH . '/modules/search/views/scripts/search_new.tpl';
		$this->_main_helper = $this->getApmHelper('selarea_pref.tpl');
		$this->_newTemplate = true;
		// JavaScript
		$this->addMetaJs('/common_new/js/import.js');
		
		// CSS
		$this->addMetaCss('/common_new/css/sub.css', array('type' => 'text/css', 'media' => 'all'));
		$this->addMetaCss('/common_new/css/jquery.qtip.css', array('type' => 'text/css', 'media' => 'all'));
		//$this->addMetaCss('/common_new/css/jquery.accessible-news-slider.css', array('type' => 'text/css', 'media' => 'all', 'rel' => 'stylesheet'));
		$this->addMetaCss('/common_new/css/top.css', array('type' => 'text/css', 'media' => 'all'));
		
		// 都道府県名取得
		$prefCd = $this->_params['PrefCd'][0];
		$this->_data['pref_name'] = Apm_Config_Shop::$PREF_LIST[$prefCd];
		
		// 探し方リンク
		$this->_data['area_search'] = array();
		$this->_data['area_search']['station'] = Apm_Bukkenurl::generateUrlByParameters($this->_params, 'station', '1');
		$this->_data['area_search']['area']    = Apm_Bukkenurl::generateUrlByParameters($this->_params, 'chiiki' , '2');
		$this->_data['area_search']['shop']    = Apm_Bukkenurl::generateUrlByParametersShop(array_merge($this->_params, array('Category'=>'2')));
		
		// こだわり一覧
		$arrKodawari = array();
		$arrKodawari = Apm_Seo::getSeoImpKodawari(0, 9999, $prefCd);
		$kodawari = array();
		foreach ($arrKodawari as $val) {
			$kodawari[$val['CD']] = $val;
		}
		ksort($kodawari);
		$this->_data['pickup_kodawari'] = $kodawari;
		// ピックアップ削除
		unset($kodawari['1']);
		unset($kodawari['2']);
		unset($kodawari['40']);
		unset($kodawari['17']);
		unset($kodawari['9']);
		unset($kodawari['6']);
		$this->_data['seo_kodawari'] = $kodawari;
		// 住居形態
		$arrType = array();
		Apm_Seo::generateTypeBlock($arrType, $this->_params, array());
		$type = array();
		foreach ($arrType['CrossType']['DATA'] as $val) {
			$key = array_search($val['DISP_NAME'], Apm_Config_Search::$TATEMONO_SYUBETU_NAME_LIST);
			$type[$key] = $val;
		}
		$this->_data['pickup_type'] = $type;
		
		// パラメータのhiddenタグ生成
		$hiddenTag = array();
		$hiddenTag['PrefCd'] = $this->_params['PrefCd'];
		$hiddenTag['SrhKbn'] = Apm_Config_Search::SRHKBN_JYUSYO;
		$this->_data['hiddenTag']  = Apm_Util::generateHiddenTag($hiddenTag);

		// 市区町村一覧
		$this->_model_sikucyoson = new Search_Model_Selsikucyoson();
		$this->_data['selcity'] = array();
		$this->_data['selcity'] = $this->_model_sikucyoson->getShikucyosonData($this->_params);
		$this->_model_sikucyoson->convertShikucyosonData($this->_data);		// 表示用データに変換
		Apm_Bukkenurl::generateSearchStaticUrl($this->_params, $this->_data['Mapping'], Apm_Config_Search::SRHKBN_JYUSYO);	// 静的URL挿入
		$this->_data['SelCyoNull'] = '0';
		$this->_selsikucyoson_helper = $this->getApmHelper('selsikucyoson_new.tpl');
		$this->_data['form_act'] = 'jyusyosearch';
		$city_block    = $this->_selsikucyoson_helper->getBlock($this->_data);
		
		//下記の削除処理は「selsikucyoson_new.tpl」の該当行が改修された際は必ず修正する事
		//「selsikucyoson_new.tpl」の「<div class="mt10 mb10">」～「</div>」を削除
		$city_block = preg_replace('/\<[d][i][v]\s[c][l][a][s][s]\=\"[m][t][1][0]\s[m][b][1][0]\"\>.*?\<\/[d][i][v]\>/is','',$city_block);
		
		//「selsikucyoson_new.tpl」の「<div id="select_area02">」～「</div>」を削除
		$city_block = preg_replace('/\<[d][i][v]\s[i][d]\=\"[s][e][l][e][c][t]\_[a][r][e][a][0][2]\"\>.*?\<\/[d][i][v]\>/is','',$city_block);

		$this->_data['city_block']    = $city_block;
		
		// ランキングリンク
		$rank_data = array();
		$rank_data['RANK_KODAWARI']   = Apm_Seo::getSeoRankingKodawari(5, 8, $prefCd);
		$rank_data['RANK_TYPE']       = Apm_Seo::getSeoRankingType(array(), $prefCd);
		$ranking_block                = $this->getApmHelper('seo_ranking_leftpanel.tpl');
		$this->_data['ranking_block'] = $ranking_block->getBlock($rank_data);
		// サジェストリンク
		$this->_data['suggestBlockData'] = Apm_Seo::getSuggestLinkBlockData($prefCd,0,20,5,15);
		$suggest_block                   = $this->getApmHelper('suggestLink.tpl');
		$this->_data['suggest_block']    = $suggest_block->getBlock($this->_data);
		// 新着物件
		$shinchaku_block = $this->getApmHelper('shinchakuLinkM.tpl');
		$shinchaku_data['shinchakuBlockData'] = Apm_Seo::getTodoufukenShinchakuBlockData($prefCd, 4);
		$shinchaku_data['shinchakuBlockData']['Title'] = $this->_data['pref_name'].'の新着物件情報をPICK UP!!';	// タイトル上書き
		$this->_data['shinchaku_blockM'] = $shinchaku_block->getBlock($shinchaku_data);
		// 前回見た物件
		$loader = new Zend_Application_Module_Autoloader(array(
			'namespace' => 'Rstobi',
			'basePath' => APPLICATION_PATH . '/modules/rstobi',
		));
		$this->_model_rireki = new Rstobi_Model_BknRireki();
		$this->_data['rireki'] = $this->_model_rireki->getRirekihyoujiData('', '0');
		$this->_data['rireki'] = $this->_model_rireki->convertRirekiData($this->_data['rireki']);
		$this->_rireki_helper  = $this->getApmHelper(APPLICATION_PATH . '/modules/rstdtl/views/helpers/rireki_new.tpl');
		$this->_data['rireki_block'] = $this->_rireki_helper->getBlock($this->_data);
	}

}
?>